'use strict';

const BaseController = require('./base');
const { addTheme } = require('../validator/theme');

class ThemeController extends BaseController {

    /**
     * 话题详情
     */
    async show() {
        const themeId = parseInt(this.ctx.params.id);
        const userId = await this.userId();
        const theme = await this.service.theme.findById(themeId, userId);
        this.ctx.helper.success({bean: theme});
    }

    /**
     * 广场话题
     * @param sex: 0-全部，1-男，2-女
     * @param type: recommend-推荐，new-最新，anonymity-匿名
     */
    async square() {
        const sex = this.ctx.query.sex;
        const type = this.ctx.query.type;
        const page = this.ctx.query.page ? parseInt(this.ctx.query.page) : 0;
        const count = this.ctx.query.count ? parseInt(this.ctx.query.count) : 15;
        const userId = await this.userId();
        const themes = await this.service.theme.squareTheme(userId, type, sex, page, count);
        this.ctx.helper.success({beans: themes});
    }

    /**
     * 用户话题
     */
    async all() {
        const userId = await this.userId();
        const categoryId = this.ctx.query.category_id ? parseInt(this.ctx.query.category_id) : 0;;
        const page = this.ctx.query.page ? parseInt(this.ctx.query.page) : 0;
        const count = this.ctx.query.count ? parseInt(this.ctx.query.count) : 15;
        const themes = await this.service.theme.findByUserId(userId, categoryId, page, count);
        this.ctx.helper.success({beans: themes});
    }

    // 新增话题
    async add() {
        const { ctx, service, app } = this;
        const errors = app.validator.validate(addTheme, ctx.request.body);
        errors && ctx.helper.commonErr('参数错误', { beans: errors });
        const id = ctx.helper.decodeJwt(ctx);
        const data = ctx.request.body;
        const res = await service.theme.addTheme({
            user_id: id,
            ...data
        });
        ctx.helper.success({bean: res}, '话题发表成功!');
    }

}

module.exports = ThemeController;